package com.game.server;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;

import lombok.Data;

import org.apache.log4j.Logger;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;

import com.comm.ISocket;
import com.comm.netty.NettyWebSocket;
import com.game.majiang.config.LogManager;
import com.game.server.message.Route;
import com.game.server.web.WebServer;

@Data
public class GameServer implements IServer {

  protected Logger log = Logger.getLogger(this.getClass().getName());

  ISocket socket;
  // 服务器是否运行
  boolean running = false;
  short port;
  static GameServer instance;

  @Override
  public void bind(short port) throws Exception {
    // socket = new MinaSocket();
    // socket.bind(port,new Route());
    this.port = port;
    socket = new NettyWebSocket();
    socket.bind(port, new Route());
    LogManager.getInstance().Log("this.port " + this.port);
  }

  @Override
  public void readConfig(String url) throws Exception {
    SAXBuilder builder = new SAXBuilder();
    Document doc = builder.build(new File(url));
    Element foo = doc.getRootElement();
    ArrayList<IConfig> list = new ArrayList<IConfig>();
    for (Element item : foo.getChildren()) {
      String path = item.getChild("path").getText();
      String className = item.getChild("class").getText();
      Class<?> cal = Class.forName(className);
      IConfig config = (IConfig) cal.newInstance();
      list.add(config);
      try {
        config.init(path);
      } catch (IOException e) {
        LogManager.getInstance().Error("加载配置文件:" + path + "出错！");
        e.printStackTrace();
      } catch (JDOMException e) {
        LogManager.getInstance().Error("解析配置文件:" + path + " 类:" + className + "出错");
        e.printStackTrace();
      }
    }
    Iterator<IConfig> entryKeyIterator = list.iterator();
    while (entryKeyIterator.hasNext()) {
      entryKeyIterator.next().finish();
    }
  }

  @Override
  public void init() throws Exception {
    WebServer.init();
    LogManager.getInstance().Log("web接口启动完毕");
  }

  @Override
  public boolean close() {
    LogManager.getInstance().Log("socket关闭");
    socket.close();

    return true;
  }

  public static GameServer getInstance() {
    if (instance == null) {
      // record = TableVo.getRecord();
      instance = new GameServer();
    }
    return instance;
  }

  @Override
  public void finish() throws Exception {
    instance = this;
    running = true;
  }
}